package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     * @param param   传入的phone
     * @return
     */

    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){ //返回值：object  包含token,isNew(boolean)
        String phone = param.get("phone");
        String verificationCode = param.get("verificationCode");

        try {
            String data = userService.login(phone,verificationCode);

            if (StringUtils.isNotEmpty(data)){
                //如果非空：    登陆成功状态！
                String[] split = StringUtils.split(data, "|");
                String token = split[0];
                String isNew = split[1];
                Map<String,Object> result = new HashMap<>();
                result.put("token",token);
                result.put("isNew",Boolean.valueOf(isNew));
                return ResponseEntity.ok(result); // 返回map  key：token,isNew   ；值：数组。。。
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("登录失败~" + e);
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }


    /**
     * 校验token，根据token查询用户数据   ()
     *
     * @param token
     * @return
     */

    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token){

        return userService.queryUserByToken(token);
    }
}
